package com.tianma315.admin.produce.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.common.base.CoreServiceImpl;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.marshalling.domain.MarshallingDO;
import com.tianma315.admin.marshalling.service.MarshallingService;
import com.tianma315.admin.material.VO.MaterialVO;
import com.tianma315.admin.material.domain.MaterialDO;
import com.tianma315.admin.material.domain.PurchaseDO;
import com.tianma315.admin.material.service.MaterialService;
import com.tianma315.admin.material.service.PurchaseService;
import com.tianma315.admin.produce.VO.ScBatFeeVO;
import com.tianma315.admin.produce.VO.ScBatchingVO;
import com.tianma315.admin.produce.dao.BatfeeMaterialDao;
import com.tianma315.admin.produce.dao.ScBatchingDao;
import com.tianma315.admin.produce.domain.*;
import com.tianma315.admin.produce.dto.MaterialForm;
import com.tianma315.admin.util.CellUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianma315.admin.produce.dao.ScBatFeeDao;
import com.tianma315.admin.produce.domain.ScBatFeeDO;
import com.tianma315.admin.produce.service.ScBatFeeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 
 * <pre>
 * 配料/投料表
 * </pre>
 * <small> 2019-12-19 15:02:35 | Aron</small>
 */
@Service
@Transactional
public class ScBatFeeServiceImpl extends CoreServiceImpl<ScBatFeeDao, ScBatFeeDO> implements ScBatFeeService {
    @Autowired
    private ScBatFeeDao scBatFeeDao;
    @Autowired
    private BatfeeMaterialDao batfeeMaterialDao;
    @Autowired
    private MaterialService materialService;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private MarshallingService marshallingService;
    @Override
    public List<ScBatFeeDO> getBatFeeDO(Integer produceTaskId) {
        Wrapper<ScBatFeeDO> wrapper = new EntityWrapper<>();
        wrapper.eq("state",0);
        wrapper.eq("produce_task_id",produceTaskId);
        List<ScBatFeeDO> scBatFeeDOList = selectList(wrapper);
        return scBatFeeDOList;
    }

    @Override
    public Page<ScBatFeeVO> getScBatFeeVO(Integer pageNumber, Integer pageSize, ScBatFeeDO scBatFeeDTO) {
        Page<ScBatFeeVO> page = new Page<>(pageNumber,pageSize);
        page.setRecords(scBatFeeDao.getScBatFeePage(scBatFeeDTO.getProduceTaskId()));
        return page;
    }

    @Override
    public boolean addScBatFeeDO(ScBatFeeVO scBatFee) {
        ScBatFeeDO scBatFeeDO = new ScBatFeeDO();
        BeanUtils.copyProperties(scBatFee,scBatFeeDO);
        scBatFeeDO.setState(0);
        if (!insert(scBatFeeDO))
            throw new MessageException("添加配料/投料单创建失败");

        for (MaterialVO ma : scBatFee.getMaterials()) {
            //添加原材料
            BatfeeMaterialDO batfeeMaterialDO = new BatfeeMaterialDO();
            batfeeMaterialDO.setBatFeeId(scBatFeeDO.getBatFeeId());
            batfeeMaterialDO.setMaterialId(ma.getMaterialId());
            //System.out.println("sullllllllllllsss=========="+ma.getBatchingSize());
            batfeeMaterialDO.setBatchingSize(ma.getBatchingSize());
            batfeeMaterialDO.setFeedingSize(ma.getFeedingSize());
            batfeeMaterialDO.setBatch(ma.getBatch());
            batfeeMaterialDO.setState(0);
            if (batfeeMaterialDao.insert(batfeeMaterialDO) != 1)
                throw new MessageException("配料&投料的原材料绑定失败");
        }
        return true;
    }

    @Override
    public boolean deleteScBatFeeVO(Integer batFeeId) {
//        ScBatFeeDO scBatFeeDO = scBatFeeDao.selectById(batFeeId);
        ScBatFeeDO scBatFeeDO = new ScBatFeeDO();
        scBatFeeDO.setState(1);
        scBatFeeDO.setBatFeeId(batFeeId);
            return updateById(scBatFeeDO);

    }

    @Override
    public HSSFWorkbook exportBatFee(String produceTaskId) {
        String[] title = {"生产任务Id（不可编辑）","班组","水温","配料水重量","出料温度","原材料名称","配料批次号","配料数量","投料数量","负责人","投料时间(2020/01/01)"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("配料&投料记录模板");

//        sheet.addMergedRegion(new CellRangeAddress(0,0,0,8));//第一行第一列开始，跨8列
        HSSFRow titleRow = sheet.createRow(0);//第0行

        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)18);
        titleStyle.setFont(font);

        //生成标题
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("配料&投料记录模板（注：红色必填项，6,7,8,9项可添加多条数据）");
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        titleCell.setCellStyle(titleStyle);

        //红色字体
        HSSFCellStyle redStyle = wb.createCellStyle();
        redStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont redFont = wb.createFont();
        redFont.setBold(true);
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        //默认字体样式
        HSSFCellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont defaultFont = wb.createFont();
        defaultFont.setBold(true);
        defaultStyle.setFont(defaultFont);

        //声明列对象
        HSSFCell cell = null;
        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        for(int i=0;i<title.length;i++){
            //下标为0,2,3,4是必填列
            if(i==2||i==3||i==4){
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(defaultStyle);
            }else {
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(redStyle);
            }
        }
        //绑定生产任务id
        HSSFRow row = sheet.createRow(2);
        row.createCell(0).setCellValue(produceTaskId);

//        List<DeviceTypeDO> list = deviceTypeService.getDeviceTypeDOList();
//        String[] deviceTypeArr = new String[list.size()];
//        for (int i = 0; i < list.size(); i++) {
//            deviceTypeArr[i] = list.get(i).getTypeName();
//        }
//        Wrapper<PurchaseDO> wrapper = new EntityWrapper<>();
//        wrapper.eq("state",0);
//        List<PurchaseDO> purchaseDOList = purchaseService.selectList(wrapper);
//        List<String> purchaseNOList = purchaseDOList.stream().map(item -> item.getPurchaseNo()).collect(Collectors.toList());
//        String[] purchaseNOArr = purchaseNOList.toArray(new String[purchaseNOList.size()]);
//        //设置设备类型为下拉框选项
//        DVConstraint purchaseNOConstraint = DVConstraint.createExplicitListConstraint(purchaseNOArr);
//        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
//        CellRangeAddressList purchaseNORegions = new CellRangeAddressList(2,
//                2, 1, 1);
//        HSSFDataValidation purchaseNOData = new HSSFDataValidation(
//                purchaseNORegions, purchaseNOConstraint);
//        sheet.addValidationData(purchaseNOData);


        List<MarshallingDO> marshallingList = marshallingService.getMarshallingList();
        List<String> marshallingNameList = marshallingList.stream().map(item -> item.getMarshallingName()).collect(Collectors.toList());
        String[] marshallingNameArr = marshallingNameList.toArray(new String[marshallingNameList.size()]);

        //设置设备类型为下拉框选项
        DVConstraint marshallingConstraint = DVConstraint.createExplicitListConstraint(marshallingNameArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList marshallingRegions = new CellRangeAddressList(2,
                2, 1, 1);
        HSSFDataValidation marshallingData = new HSSFDataValidation(
                marshallingRegions, marshallingConstraint);
        sheet.addValidationData(marshallingData);

        List<MaterialDO> materialDOS = materialService.getMaterialList();
        List<String> materialList = materialDOS.stream().map(item -> item.getMaterialName()).collect(Collectors.toList());
        String[] materialNameArr = materialList.toArray(new String[materialList.size()]);

        //设置设备类型为下拉框选项
        DVConstraint constraint = DVConstraint.createExplicitListConstraint(materialNameArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(2,
                10000, 5, 5);
        HSSFDataValidation materialData = new HSSFDataValidation(
                regions, constraint);
        sheet.addValidationData(materialData);


        return wb;
    }

    @Override
    public void importBatFee(MultipartFile file, Long userId) {
        Boolean flag = CellUtil.isExcel(file.getOriginalFilename());
        if (!flag){
            throw new MessageException("只支持Excel文件");
        }

        Wrapper<PurchaseDO> wrapper = new EntityWrapper<>();
        wrapper.eq("state",0);
        List<PurchaseDO> purchaseDOList = purchaseService.selectList(wrapper);
        List<MaterialDO> materialDOList = materialService.getMaterialList();
        List<MarshallingDO> marshallingList = marshallingService.getMarshallingList();

        try {
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum(); //返回行数下标 从0开始
            //判断原材料项是否有重复值
            List<String> materialList = new ArrayList<>();
            for (int i = 2; i <= rowNum; i++) {
                Row rows = sheet.getRow(i);
                Cell materialCell = rows.getCell(5);
                materialList.add(materialCell.getStringCellValue());
            }
            Set<String> set = new HashSet<>(materialList);
            if (materialList.size()!=set.size()){
                throw new MessageException("原料不能重复");
            }

            //前两行都不是内容，所以从2开始
            Row row = sheet.getRow(2);
//            short num = row.getLastCellNum();
            //配料&投料数据导入
            ScBatFeeDO scBatFeeDO = new ScBatFeeDO();
            scBatFeeDO.setState(0);
            scBatFeeDO.setCreateDate(Calendar.getInstance().getTime());
            scBatFeeDO.setCreateBy(userId);
//            ScAdditiveDO scAdditiveDO = new ScAdditiveDO();
//            scAdditiveDO.setState(0);
//            scAdditiveDO.setCreateBy(userId);
//            scAdditiveDO.setCreateDate(Calendar.getInstance().getTime());
            Cell produceTaskIdCell = row.getCell(0);
            if (CellUtil.isCellEmpty(produceTaskIdCell)){
                throw new MessageException("生产任务Id不能为空");
            }
            scBatFeeDO.setProduceTaskId(Integer.parseInt(produceTaskIdCell.getStringCellValue()));

//            Cell purchaseIdCell = row.getCell(1);
//            if (CellUtil.isCellEmpty(purchaseIdCell)){
//                throw new MessageException("配料批次号不能为空");
//            }
//            List<PurchaseDO> purchaseFilterResult = purchaseDOList.stream()
//                    .filter(item -> item.getPurchaseNo().equals(purchaseIdCell.getStringCellValue()))
//                    .collect(Collectors.toList());
//            scBatFeeDO.setPurchaseId(purchaseFilterResult.get(0).getPurchaseId());

            Cell marshallingIdCell = row.getCell(1);
            if (CellUtil.isCellEmpty(marshallingIdCell)){
                throw new MessageException("班组项不能为空");
            }
            List<MarshallingDO> marshallingFilterResult = marshallingList.stream()
                    .filter(item -> item.getMarshallingName().equals(marshallingIdCell.getStringCellValue()))
                    .collect(Collectors.toList());
            scBatFeeDO.setMarshallingId(marshallingFilterResult.get(0).getMarshallingId());

            Cell temperatureCell = row.getCell(2);
            if (temperatureCell!=null){
                temperatureCell.setCellType(CellType.STRING);
               scBatFeeDO.setTemperature(Double.parseDouble(temperatureCell.getStringCellValue()));
            }
            Cell waterWeightCell = row.getCell(3);
            if (waterWeightCell!=null){
                waterWeightCell.setCellType(CellType.STRING);
                scBatFeeDO.setWaterWeight(Double.parseDouble(waterWeightCell.getStringCellValue()));
            }Cell outTemperatureCell = row.getCell(4);
            if (outTemperatureCell!=null){
                outTemperatureCell.setCellType(CellType.STRING);
                scBatFeeDO.setOutTemperature(Double.parseDouble(outTemperatureCell.getStringCellValue()));
            }

            Cell feedingDateCell = row.getCell(10);
            if (feedingDateCell==null){
                throw new MessageException("投料时间不能为空");
            }
            scBatFeeDO.setFeedingDate(feedingDateCell.getDateCellValue());

            Cell leadingOfficialCell = row.getCell(9);
            if (CellUtil.isCellEmpty(leadingOfficialCell)){
                throw new MessageException("投料人不能为空");
            }
            scBatFeeDO.setLeadingOfficial(leadingOfficialCell.getStringCellValue());
            insert(scBatFeeDO);
            //添加剂原材料绑定数据导入
            for (int i = 2; i <= rowNum; i++) {
                Row rows = sheet.getRow(i);
                BatfeeMaterialDO batfeeMaterialDO = new BatfeeMaterialDO();
                batfeeMaterialDO.setBatFeeId(scBatFeeDO.getBatFeeId());

                Cell materialCell = rows.getCell(5);
                if (CellUtil.isCellEmpty(materialCell)){
                    throw new MessageException("原材料不能为空");
                }
                List<MaterialDO> materialFilterResult = materialDOList.stream()
                        .filter(item -> item.getMaterialName().equals(materialCell.getStringCellValue()))
                        .collect(Collectors.toList());
                batfeeMaterialDO.setMaterialId(materialFilterResult.get(0).getMaterialId());

                Cell batchCell = rows.getCell(6);
                if (CellUtil.isCellEmpty(batchCell)){
                    throw new MessageException("配料批次号不能为空");
                }
                batfeeMaterialDO.setBatch(batchCell.getStringCellValue());

                Cell batchingSizeCell = rows.getCell(7);
                if (CellUtil.isCellEmpty(batchingSizeCell)){
                    throw new MessageException("配料数量不能为空");
                }
                batfeeMaterialDO.setBatchingSize(Double.parseDouble(batchingSizeCell.getStringCellValue()));
                Cell feedingSizeCell = rows.getCell(8);
                if (CellUtil.isCellEmpty(feedingSizeCell)){
                    throw new MessageException("投料数量不能为空");
                }
                batfeeMaterialDO.setFeedingSize(Double.parseDouble(feedingSizeCell.getStringCellValue()));

                if (batfeeMaterialDao.insert(batfeeMaterialDO) != 1)
                    throw new MessageException("配料&投料原材料绑定失败");
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public ScBatFeeVO selectVOById(Integer batFeeId) {
        ScBatFeeVO scBatFeeVO = scBatFeeDao.selectVOById(batFeeId);
        return scBatFeeVO;
    }

    @Override
    public void updateScBatFeeVOById(ScBatFeeVO scBatFeeVO) {
        //更新数据
        ScBatFeeDO scBatFeeDO = new ScBatFeeDO();
        BeanUtils.copyProperties(scBatFeeVO,scBatFeeDO);
        scBatFeeDO.setState(0);
        scBatFeeDao.updateById(scBatFeeDO);
        //删除关联数据和添加新数据（修改关联数据）
        Wrapper<BatfeeMaterialDO> wrapper = new EntityWrapper<>();
        wrapper.eq("bat_fee_id",scBatFeeVO.getBatFeeId());
        batfeeMaterialDao.delete(wrapper);


        for (MaterialVO ma : scBatFeeVO.getMaterials()) {
            //添加原材料
            BatfeeMaterialDO batfeeMaterialDO = new BatfeeMaterialDO();
            batfeeMaterialDO.setBatFeeId(scBatFeeDO.getBatFeeId());
            batfeeMaterialDO.setMaterialId(ma.getMaterialId());
            //System.out.println("sullllllllllllsss=========="+ma.getBatchingSize());
            batfeeMaterialDO.setBatchingSize(ma.getBatchingSize());
            batfeeMaterialDO.setFeedingSize(ma.getFeedingSize());
            batfeeMaterialDO.setBatch(ma.getBatch());
            batfeeMaterialDO.setState(0);
            if (batfeeMaterialDao.insert(batfeeMaterialDO) != 1)
                throw new MessageException("配料&投料的原材料修改失败");
        }
    }
}
